/**
 * FileName: BookingController
 * Author:   Leopold
 * Date:     2018/9/11 16:12
 * Description: 预约流程
 * History:
 */
package cn.mcsys.viewer.core.web;

import cn.mcsys.myadmin.common.service.ServiceException;
import cn.mcsys.myadmin.common.utils.StringUtils;
import cn.mcsys.myadmin.common.web.JsonResult;
import cn.mcsys.myadmin.dubbo.service.BackService;
import cn.mcsys.myadmin.modules.air.entity.AirRidePoint;
import cn.mcsys.myadmin.modules.air.entity.AirSendMessage;
import cn.mcsys.myadmin.modules.viewer.entity.*;
import cn.mcsys.viewer.core.service.AirShowIndexService;
import cn.mcsys.viewer.core.utils.HttpRequestLocal;
import cn.mcsys.viewer.core.web.vo.AirPointVO;
import cn.mcsys.viewer.core.web.vo.AirQrCodeVO;
import cn.mcsys.viewer.core.web.vo.AirSelectPointVO;
import cn.mcsys.viewer.core.web.vo.AirShowIndexVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("booking")
public class BookingController {

//    public static Map<Integer,List<AirRideQrCode>> qrCodeMap = new HashMap<>();

    @Autowired
    private AirShowIndexService airShowIndexService;

    @Autowired
    private BackService backService;

    private static Logger logger = LoggerFactory.getLogger(BookingController.class);

    /**
     * 首页页面(查询出没过期的二维码)暂时使用currentHashMap
     *
     * @return
     */
    @RequestMapping("/index")
    @ResponseBody
    public JsonResult index() {
        AirViewerUser user = HttpRequestLocal.getUserSession();
        AirShowIndexVO vo = new AirShowIndexVO();
        String dayMsg = "";
        try {
            dayMsg = airShowIndexService.airshowIndex();
        } catch (ParseException e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
        List<AirETickets> tickets = backService.selectMyAllETickets(user.getId());
        Integer eticketSize = tickets.size();

//        Integer eticketSize = null;
//        String etickets = JedisUtilsViewer.get(JedisUtilsViewer.createEticketsKey(user.getId()));
//        if(eticketSize != null){
//            eticketSize = Integer.parseInt(etickets);
//        }else {
//            List<AirETickets> tickets = backService.selectMyAllETickets(user.getId());
//            eticketSize = tickets.size();
//            JedisUtilsViewer.set(JedisUtilsViewer.createEticketsKey(user.getId()),eticketSize.toString(),86400);
//        }

        List<AirRideQrCode> rideQrCodes = backService.selectByUserQRCodeId(user.getId());

//        List<AirRideQrCode>  rideQrCodes = null;
//        String qrcodes = JedisUtilsViewer.get(JedisUtilsViewer.createQrCodesKey(user.getId()));
//        if (qrcodes != null){
//            rideQrCodes = JSONArray.parseArray(qrcodes, AirRideQrCode.class);
//        }else {
//            rideQrCodes = backService.selectByUserQRCodeId(user.getId());
//            JedisUtilsViewer.set(JedisUtilsViewer.createQrCodesKey(user.getId()), JSON.toJSONString(rideQrCodes),86400);
//        }
        vo.setTicketCount(eticketSize);
        vo.setQrCodeList(rideQrCodes);
        vo.setDayMsg(dayMsg)
        ;
        return JsonResult.success(vo);
    }

    /**
     * 选择当前乘车点
     *
     * @param lon 经度
     * @param lat 纬度
     * @return
     */
    @GetMapping("getNearRidePoints")
    @ResponseBody
    public JsonResult selectNearPoint(Double lon, Double lat, Integer type) {
        if (lon == null || lat == null) {
            return JsonResult.emptyParameter800();
        }

        List<AirRidePoint> points = backService.selectAllPoint();
        if(type != null) {
            if (type == 3 || type == 4) {
                points = backService.selectByPointType(type);
            }
        }
        AirSelectPointVO airSelectPointVO = null;
        try {
            airSelectPointVO = airShowIndexService.setNearPoint(lon, lat, points);
        } catch (Exception e) {
            return JsonResult.fail();
        }
        return JsonResult.success(airSelectPointVO);

    }

    /**
     * 获取所有的乘车
     *
     * @return
     */
    @GetMapping("getRidePoints")
    @ResponseBody
    public JsonResult selectPoint() {
        List<AirRidePoint> points = backService.selectAllPoint();
        return JsonResult.success(points);
    }

    /**
     * 生成电子票(将状态设置为status设置为0),查询的时候查询未过期的
     *
     * @return
     */
    @PostMapping("createETicket")
    @ResponseBody
    public JsonResult createETicket(Integer type, String number) {
        if (type == null || number == null) {
            return JsonResult.emptyParameter800();
        }
        AirViewerUser user = HttpRequestLocal.getUserSession();
        //查询是否有对应的票务
        List<AirTickets> airTickets = backService.selectByTypeAndNumber(type, number.trim());
        if (airTickets == null || airTickets.size() == 0) {
            return JsonResult.failMessage("没有该票务信息");
        }
        backService.saveETicket(airTickets, user);
        List<AirETickets> airETickets = backService.selectMyAllETickets(user.getId());
//        设置redis的ip和端口
//        重新设置缓存
//        JedisUtilsViewer.set(JedisUtilsViewer.createEticketsKey(user.getId()), String.valueOf(airETickets.size()),86400);
        return JsonResult.success(airTickets);
    }


    /**
     * 获取个人所有的电子票(判断是否过期,过期的电子票不能生成二维码),查询没有二维码id的,在生成二维码页面
     *
     * @return
     */
    @GetMapping("getTickets")
    @ResponseBody
    public JsonResult getTickets() {
        AirViewerUser user = HttpRequestLocal.getUserSession();
        List<AirETickets> eTicketsList = new ArrayList<>();
        List<AirETickets> airETickets = backService.selectETicketsByUserId(user.getId());
        List bookingDate = new ArrayList();
        for (AirETickets airETicket : airETickets) {
            if (airETicket.getAirRideQrCode() == null) {
                eTicketsList.add(airETicket);
            }
            String ticketDate = airETicket.getTicketDate();
            if (bookingDate.contains(ticketDate)) {
                continue;
            }
            bookingDate.add(ticketDate);
        }
        Map map = new HashMap();
        map.put("tickets", eTicketsList);
        map.put("bookDate", bookingDate);
        return JsonResult.success(map);
    }

    /**
     * 查询个人所有的电子票,包含过期的
     *
     * @return
     */
    @RequestMapping("getMyAllTickets")
    @ResponseBody
    public JsonResult getMyAllTickets() {
        AirViewerUser user = HttpRequestLocal.getUserSession();
        return JsonResult.success(backService.selectMyAllETickets(user.getId()));
    }

    /**
     * 生成乘车二维码,不能超过9人,票的日期和乘车日期的一致,生成过的二维码可不可以再生成?
     *
     * @param eTicketsIds
     * @param bookingDate
     * @param phone
     * @return
     */
    @PostMapping("createQrCode")
    @ResponseBody
    public JsonResult createQrCode(Long ridePointId, Long[] eTicketsIds, String bookingDate, String phone) {
        System.out.println("ridePointId:" + ridePointId + ",eTicketsIds:" + eTicketsIds.length + ",bookingDate=" + bookingDate + ",phone=" + phone);
        if (ridePointId == null || eTicketsIds.length == 0 || bookingDate == null || phone == null) {
            return JsonResult.emptyParameter800();
        }
        System.out.println("判断是否是同一天开始");
        try {
//        判断选的是否是同一天
            backService.isSameDay(eTicketsIds, bookingDate);
        } catch (ServiceException e) {
            return JsonResult.notSameDay801();
        } catch (ParseException e) {
            e.printStackTrace();
            return JsonResult.fail();
        }
        System.out.println("判断是否是同一天结束");
        if (eTicketsIds.length > 9) {
            return JsonResult.tooManyPeople803();
        }
        AirViewerUser user = HttpRequestLocal.getUserSession();
        if (user.getOpenid() != null) {
            System.out.println("获取微信用户信息：" + user.getOpenid());
        } else if (user.getUsername() != null) {

            System.out.println("获取APP用户信息：" + user.getUsername());
        }
//        新增二维码对象
        List<Long> longs = StringUtils.arrayTest2(eTicketsIds);
        ArrayList<Long> list = new ArrayList<>();
        Long[] eticklongs = new Long[longs.size()];
        Long[] longs1 = list.toArray(eticklongs);

        System.out.println("二维码保存开始");
        AirRideQrCode airRideQrCode = backService.save(ridePointId, longs1, bookingDate, phone, user);
        System.out.println("二维码保存结束");
//        更改电子票的所属的二维码
        System.out.println("更新保存开始");
        backService.setQrCodeId(eTicketsIds, airRideQrCode);
        System.out.println("更新保存结束");
//        查询出所有该用户没过期和没使用的二维码
//        List<AirRideQrCode> airRideQrCodes = backService.selectByUserQRCodeId(user.getId());

//        JedisUtilsViewer.set(JedisUtilsViewer.createQrCodesKey(user.getId()), JSON.toJSONString(airRideQrCodes),86400);

//        AirRidePoint airRidePoint = backService.selectPointById(airRideQrCode.getAirRidePoint().getId());
        System.out.println("设置VO开始");
        AirQrCodeVO airQrCodeVO = new AirQrCodeVO();
        airQrCodeVO.setAirRideQrCode(airRideQrCode);
        airQrCodeVO.setRidePoint(airRideQrCode.getAirRidePoint());
        if ("珠海".equalsIgnoreCase(airRideQrCode.getAirRidePoint().getCity())) {
            airQrCodeVO.setZhuHaiCity(true);
        }
        return JsonResult.success(airQrCodeVO);
    }

    /**
     * 查询是否在停车场范围内
     *
     * @param lon
     * @param lat
     * @return
     */
    @GetMapping("nowLocation")
    @ResponseBody
    public JsonResult nowLocation(Double lon, Double lat) {
        if (lon == null || lat == null) {
            return JsonResult.emptyParameter800();
        }
//        查询是否在某一个停车场内(P6-P11)
        String parkingLotName = airShowIndexService.isInParkingLot(lon, lat);
        if (parkingLotName == null) {
            return JsonResult.notPakringLot802();
        }
        return JsonResult.successMessage(parkingLotName);
    }

    /**
     * 记录车辆经纬度
     *
     * @param lon
     * @param lat
     * @return
     */
    @PostMapping("nowLocation")
    @ResponseBody
    public JsonResult recordNowLocation(Double lon, Double lat) {
        if (lon == null || lat == null) {
            return JsonResult.emptyParameter800();
        }
        AirParkingLocation airParkingLocation = null;
        try {
            airParkingLocation = airShowIndexService.saveLocation(lon, lat);
        } catch (Exception e) {
            return JsonResult.failMessage(e.getMessage());
        }
        return JsonResult.success(airParkingLocation);
    }

    @GetMapping("getParkingLocation")
    @ResponseBody
    public JsonResult getParkingLocation(Long airParkingLocationId){
        if(airParkingLocationId == null){
            return JsonResult.emptyParameter800();
        }
        AirParkingLocation airParkingLocation = backService.getParkingLocation(airParkingLocationId);
        return JsonResult.success(airParkingLocation);
    }



    @RequestMapping("cancelBooking")
    @ResponseBody
    public JsonResult cancelBooking(Long qrcodeId) {
        System.out.println("==================进入取消预约=====================");
        System.out.println("qrcodeId:" + qrcodeId);
        AirViewerUser user = HttpRequestLocal.getUserSession();
        backService.cancelBooking(qrcodeId, user.getId());
        return JsonResult.success();
    }

    /**
     * 获取实时消息
     *
     * @return
     */
    @GetMapping("getMessage")
    @ResponseBody
    public JsonResult getRealMessage() {
        List<AirSendMessage> messages = backService.SelectAirUserMessage();
        return JsonResult.success(messages);
    }

    /**
     * 导航所需的乘车点
     *
     * @param qrcodeId
     * @return
     */
    @GetMapping("getAllPoint")
    @ResponseBody
    public JsonResult getAllPoint(Long qrcodeId) {
        AirRidePoint nowAirRidePoint = null;
        AirPointVO airPointVO = new AirPointVO();
        if (qrcodeId != null) {
            nowAirRidePoint = backService.selectByQrId4Point(qrcodeId);
            airPointVO.setNowAiRidePoint(nowAirRidePoint);
        }
        List<AirRidePoint> points = backService.selectAllPoint();
        airPointVO.setAllAirRidePoint(points);
        return JsonResult.success(airPointVO);
    }

    /**
     * 判断微信用户还是App用户
     * 200:微信用户，500App用户
     */
    @GetMapping("whereUser")
    @ResponseBody
    public JsonResult whereUser() {
        AirViewerUser user = HttpRequestLocal.getUserSession();
        if (user.getOpenid() != null) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    /**
     * 获取对应类型的乘车点
     *
     * @param type 3酒店预约，4港珠澳预约
     * @return
     */
    @GetMapping("HotelPointAndGZABridge")
    @ResponseBody
    public JsonResult getHotelPoint(Integer type) {
        List<AirRidePoint> points = backService.selectByPointType(type);
        return JsonResult.success(points);
    }

    /**
     * 酒店预约和港珠澳预约
     *
     * @param pointId     3酒店预约，4港珠澳预约
     * @param eTicketsIds 电子票id
     * @param phone       电话号
     * @return
     */
    @PostMapping("HotelPointAndGZABridge")
    @ResponseBody
    public JsonResult bookingHotelAndGZABridge(Integer pointId, String bookingDate, Long[] eTicketsIds, String phone) {
        if (pointId == null || eTicketsIds == null || phone == null) {
            return JsonResult.emptyParameter800();
        }
        AirViewerUser user = HttpRequestLocal.getUserSession();
        List<Long> longs = StringUtils.arrayTest2(eTicketsIds);
        ArrayList<Long> list = new ArrayList<>();
        Long[] eticklongs = new Long[longs.size()];
        Long[] longs1 = list.toArray(eticklongs);

        AirRideQrCode airRideQrCode = backService.bookingHotelPointAndGZABridge(user, pointId, bookingDate, longs1, phone);
        AirQrCodeVO airQrCodeVO = new AirQrCodeVO();
        airQrCodeVO.setAirRideQrCode(airRideQrCode);
        airQrCodeVO.setRidePoint(airRideQrCode.getAirRidePoint());
        airQrCodeVO.setZhuHaiCity(true);
        return JsonResult.success(airQrCodeVO);
    }


    @RequestMapping("test")
    @ResponseBody
    public JsonResult test() {
        return JsonResult.success();
    }


    @RequestMapping("createPicture")
    @ResponseBody
    public JsonResult batchPicture() {
//        List<AirRideQrCode> airRideQrCodes = backService.selectAllQrCode(pageNo);
//        backService.batchcreatepicture(airRideQrCodes);
        return JsonResult.success();
    }
}
